<template>
  <div class="upload-img">
    <el-upload
      class="avatar-uploader"
      :action="action"
      :show-file-list="false"
      :on-success="handleSuccess"
      :before-upload="beforeUpload"
      :headers="headers"
      :data="data"
      :on-error="handleError"
      :on-progress="handleProgress"
      :disabled="disabled"
    >
      <div v-if="modelValue" class="avatar-preview">
        <el-avatar :src="modelValue" :size="avatarSize" />
        <div v-if="!disabled" class="avatar-overlay">
          <el-icon><Edit /></el-icon>
          <span>更换图片</span>
        </div>
      </div>
      <div v-else class="avatar-uploader-placeholder">
        <el-icon class="avatar-uploader-icon"><Plus /></el-icon>
        <div class="placeholder-text">点击上传图片</div>
      </div>

      <template #tip>
        <div class="el-upload__tip">支持 JPG、PNG 格式，大小不超过 2MB</div>
      </template>
    </el-upload>

    <!-- 上传进度提示 -->
    <el-dialog
      v-model="progressVisible"
      title="上传中"
      width="400px"
      :close-on-click-modal="false"
      :show-close="false"
    >
      <el-progress :percentage="uploadPercentage" />
      <template #footer>
        <el-button @click="cancelUpload">取消</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { defineProps, defineEmits, ref } from 'vue';
import { Plus, Edit } from '@element-plus/icons-vue';
import { ElMessage } from 'element-plus';

// Vite env variables are available via import.meta.env directly

interface Props {
  modelValue?: string;
  action: string;
  headers?: Record<string, string>;
  data?: Record<string, any>;
  avatarSize?: number;
  disabled?: boolean;
}

// 下方类型禁用eslint的no-unused-vars规则
/* eslint-disable no-unused-vars */
interface Emits {
  (e: 'update:modelValue', value: string): void;
  (e: 'change', value: string): void;
  (e: 'success', response: any): void;
  (e: 'error', error: any): void;
}

const props = withDefaults(defineProps<Props>(), {
  avatarSize: 100,
  disabled: false
});

const emit = defineEmits<Emits>();

const progressVisible = ref(false);
const uploadPercentage = ref(0);
let uploadController: AbortController | null = null;

// 支持的图片格式
const supportedFormats = [
  'image/jpeg',
  'image/jpg',
  'image/png',
  'image/gif',
  'image/webp'
];

// es
function beforeUpload(file: File) {
  const isImage = file.type.startsWith('image/');
  const isSupportedFormat = supportedFormats.includes(file.type);
  const isLt2M = file.size / 1024 / 1024 < 2;

  if (!isImage) {
    ElMessage.error('只能上传图片格式!');
    return false;
  }

  if (!isSupportedFormat) {
    ElMessage.error('支持的图片格式: JPG、PNG、GIF、WebP!');
    return false;
  }

  if (!isLt2M) {
    ElMessage.error('图片大小不能超过 2MB!');
    return false;
  }

  // 开始上传，显示进度
  progressVisible.value = true;
  uploadPercentage.value = 0;

  // 创建 AbortController 用于取消上传
  uploadController = new AbortController();

  return isImage && isSupportedFormat && isLt2M;
}

function handleSuccess(response: any) {
  progressVisible.value = false;
  uploadPercentage.value = 0;

  // 根据常见的后端响应格式处理
  const imageUrl = import.meta.env.VITE_APP_API_LOAD_URL + response.data?.url;
  if (imageUrl) {
    emit('update:modelValue', imageUrl);
    emit('change', imageUrl);
    emit('success', response);
    ElMessage.success('图片上传成功');
  } else {
    emit('error', new Error('未获取到图片地址'));
  }
}

function handleError(error: any) {
  progressVisible.value = false;
  uploadPercentage.value = 0;

  const errorMessage = error?.message || '上传失败，请重试';
  ElMessage.error(errorMessage);
  emit('error', error);
}

function handleProgress(event: any) {
  if (event.percent) {
    uploadPercentage.value = Math.floor(event.percent);
  }
}

function cancelUpload() {
  if (uploadController) {
    uploadController.abort();
    uploadController = null;
  }
  progressVisible.value = false;
  uploadPercentage.value = 0;
  ElMessage.info('已取消上传');
}

// 清除当前图片
// function clearImage() {
//   ElMessageBox.confirm('确定要删除这张图片吗？', '提示', {
//     type: 'warning',
//     confirmButtonText: '确定',
//     cancelButtonText: '取消'
//   })
//     .then(() => {
//       emit('update:modelValue', '');
//       emit('change', '');
//       ElMessage.success('图片已删除');
//     })
//     .catch(() => {
//       // 用户取消删除
//     });
// }
</script>

<style scoped lang="scss">
.upload-img {
  .avatar-uploader {
    display: flex;
    flex-direction: column;
    :deep(.el-upload) {
      border: 1px dashed #d9d9d9;
      border-radius: 6px;
      cursor: pointer;
      position: relative;
      overflow: hidden;
      transition: all 0.3s;
      width: 100px;

      &:hover {
        border-color: #409eff;
      }

      &.is-disabled {
        cursor: not-allowed;
        opacity: 0.6;

        &:hover {
          border-color: #d9d9d9;
        }
      }
    }
  }

  .avatar-preview {
    position: relative;
    display: inline-block;

    &:hover .avatar-overlay {
      opacity: 1;
    }

    .avatar-overlay {
      position: absolute;
      top: 0;
      left: 0;
      right: 0;
      bottom: 0;
      background: rgba(0, 0, 0, 0.5);
      display: flex;
      flex-direction: column;
      justify-content: center;
      align-items: center;
      color: white;
      opacity: 0;
      transition: opacity 0.3s;
      border-radius: 6px;

      .el-icon {
        font-size: 20px;
        margin-bottom: 4px;
      }

      span {
        font-size: 12px;
      }
    }
  }

  .avatar-uploader-placeholder {
    width: v-bind('props.avatarSize + "px"');
    height: v-bind('props.avatarSize + "px"');
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    color: #8c939d;
    cursor: pointer;

    .avatar-uploader-icon {
      font-size: 28px;
      margin-bottom: 8px;
    }

    .placeholder-text {
      font-size: 12px;
      text-align: center;
    }
  }

  .el-upload__tip {
    margin-top: 8px;
    color: #909399;
    font-size: 12px;
  }
}
</style>
